package learnning.dao;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Query;

import learnning.dao.base.HibernateDao;
import learnning.entity.Advert;
import learnning.entity.Category;
import learnning.entity.User;

public class AdvertDao extends HibernateDao {
	public void addAdvert(String userName, String categoryTitle, String title,
			String message) {
		try {
			begin();
			Query query = getSession().createQuery(
					"from User where name = :username");
			query.setString("username", userName);
			User user = (User) query.uniqueResult();

			Query query2 = getSession().createQuery(
					"from Category where title = :title");
			query2.setString("title", categoryTitle);
			Category category = (Category) query2.uniqueResult();

			Advert advert = new Advert(title, message, user);
			getSession().save(advert);

			Set<Advert> adverts = new HashSet<Advert>();
			adverts.add(advert);
			category.setAdverts(adverts);
			getSession().save(category);
			commit();
		} catch (HibernateException e) {
			rollback();
			e.printStackTrace();
		}
	}
}
